const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const { setAccessToken, setRefreshToken, secret } = require('../utils/token')
const { DataTypes, Sequelize } = require('sequelize')
const smsu = require('../utils/sendMsg')
const nodemailer = require('nodemailer')
const path = require('path')
const sequelize = new Sequelize('jiaju', 'root', 'rootroot', {
    host: '192.168.1.115',
    dialect: 'mysql'/* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */
});
const User = sequelize.define('user', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    // 在这里定义模型属性
    username: {
        type: DataTypes.STRING,
        allowNull: false
    },
    password: {
        type: DataTypes.STRING
    },
    email: {
        type: DataTypes.STRING
    },
    avatar: {
        type: DataTypes.STRING
    },
    phone: {
        type: DataTypes.STRING
    }
}, {
    // 这是其他模型参数
    timestamps: false,
    freezeTableName: true
});
(async () => {
    await sequelize.sync();
})();
router.prefix('/zzq')

// 登录
router.post('/login', async (ctx) => {
    console.log(ctx.request.body);
    let { pass, user } = ctx.request.body
    const project = await User.findOne({ where: { username: user } });
    if (project === null) {
        ctx.body = { code: 100, msg: '用户名不正确' };
    } else {
        const project1 = await User.findOne({ where: { username: user, password: pass } });
        if (project1 === null) {
            ctx.body = { code: 300, msg: '密码不正确' };
        } else {
            ctx.body = {
                code: 200, data: {
                    accessToken: setAccessToken({ token: project1.id }),
                    refreshToken: setRefreshToken({ token: project1.id })
                },
                msg: '登录成功，获取到token'
            };
        }
    }
})
// 手机验证码
router.post('/regCode', async function (ctx, next) {
    let { phone } = ctx.request.body
    console.log(phone);
    const project = await User.findOne({ where: { phone } });
    if (project === null) {
        ctx.body = { code: 100, msg: "手机没注册" }
    } else {
        let randomCode = ((Math.random() * 9 + 1) * 1000).toFixed(0); //4位随机数验证码
        let content = "{\"code\":\"" + randomCode + "\"}"; //短信内容
        // smsu.send(phone, 'myapp', 'SMS_462635376', content); //调用发送短信方法

        ctx.body = {
            code: 200, data: {
                randomCode,
                accessToken: setAccessToken({ token: project.id }),
                refreshToken: setRefreshToken({ token: project.id })
            }, msg: '登录成功'
        }
    }
})
// 邮箱验证码验证
router.post('/emailCode', async function (ctx, next) {
    let { email } = ctx.request.body
    console.log(email);
    // 创建SMTP传输对象
    const transporter = nodemailer.createTransport({
        host: 'smtp.qq.com', // 发送方邮箱 qq 通过lib/wel-konw
        port: 465,
        secure: true, // true for 465, false for other ports
        service: 'qq',
        auth: {
            user: email,
            pass: 'reircgwjxwmhjgch',
        },
    });
    // 生成随机验证码
    let randomCode = ((Math.random() * 9 + 1) * 1000).toFixed(0);
    try {
        // 发送邮件
        // await transporter.sendMail({
        //     from: '1225852936@qq.com',
        //     to: email,
        //     subject: '邮箱验证码',
        //     text: `你的验证码是：${randomCode}`,
        // });
        // 返回成功响应
        ctx.body = {
            code: 200, data: { randomCode }, msg: '成功'
        }
    } catch (error) {
        // 返回错误响应
        ctx.body = { success: false, error: 'Failed to send verification email' };
    }
})
// 邮箱验证
router.post('/email', async function (ctx, next) {
    let { email } = ctx.request.body
    const project = await User.findOne({ where: { email } });
    if (project === null) {
        ctx.body = { code: 100, msg: "邮箱没注册" }
    } else {
        ctx.body = { code: 200, msg: '邮箱存在', data: project }
    }
})

// 验证token
router.post('/refresh', (ctx) => {
    //获取请求头中携带的长token
    let r_tk = ctx.request.headers.pass
    const decoded = jwt.verify(r_tk, secret);
    //解析token 参数 token 密钥 回调函数返回信息
    jwt.verify(r_tk, secret, (error) => {
        if (error) {
            ctx.body = {
                code: 4006,
                msg: '长token无效，请重新登录'
            }
        } else {
            ctx.body = {
                code: 2000,
                msg: '长token有效，返回新的token',
                data: {
                    accessToken: setAccessToken({ token: decoded.token }),
                    refreshToken: setAccessToken({ token: decoded.token })
                }
            }
        }
    })
})

// 修改密码
router.post('/setpass', async (ctx) => {
    // console.log(ctx.request.body);
    let { password, email } = ctx.request.body
    await User.update({ password }, {
        where: {
            email
        }
    });
    ctx.body = { code: 200, msg: '修改密码成功,请重新登录！' }
})

// 注册验证
router.post('/Account', async (ctx) => {
    let { username, email, phone } = ctx.request.body
    const project = await User.findOne({ where: { username } });
    if (project) {
        ctx.body = { code: 100, msg: '用户名已存在' };
    } else {
        const project1 = await User.findOne({ where: { email } });
        if (project1) {
            ctx.body = { code: 300, msg: '邮箱已存在' };
        } else {
            const project2 = await User.findOne({ where: { phone } });
            if (project2) {
                ctx.body = { code: 400, msg: '手机号已存在' };
            } else {

                ctx.body = { code: 200, msg: '账号可用,请设置密码！', data: ctx.request.body }
            }
        }
    }

})
// 注册账号
router.post('/Accountpass', async (ctx) => {
    // console.log(ctx.request.body);
    let { username, email, phone, img, password } = ctx.request.body
    const jane = await User.create({ username, email, phone, avatar: img, password });
    if (jane) ctx.body = { code: 200, msg: '注册成功,请重新登录！' }


})
// 上传头像
router.post('/upload', async (ctx) => {
    const { file } = ctx.request.files;
    const fileTypes = ["image/jpeg", "image/png"]
    if (file) {
        if (fileTypes.includes(file.mimetype)) {
            ctx.body = { code: 200, msg: '上传成功', data: { url: file.newFilename } }
        } else {
            ctx.body = { code: 100, msg: '上传图片非jpg 和 png 格式' }
        }

    } else {
        ctx.body = { code: 300, msg: '上传出错' }
    }
})

module.exports = router
